package cn.stronglink.assetmanage.business.check.assetlist;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.PowerManager;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.stronglink.assetmanage.BaseActivity;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.check.detail.AddCheckDetailActivity;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.entity.MessageEvent;
import cn.stronglink.assetmanage.entity.OrderType;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.listener.ITaskSyncListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.PrefUtils;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.utils.dao.BaseDataUtil;
import cn.stronglink.assetmanage.utils.dao.CheckDataUtil;
import cn.stronglink.assetmanage.utils.net.TaskSyncModel;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;

/**
 * 未入库资产列表页面
 */
public class AssetListActivity extends BaseActivity implements View.OnClickListener, ITaskSyncListener {
    //单号，创建日期，总数
    private TextView tv_uncheck_order_no, tv_uncheck_order_create_date, tv_uncheck_total;
    //地点
    private Spinner spLocation;
    private TabLayout tl_uncheck_asset_list;
    private ViewPager vp_uncheck_asset_list;
    private UncheckAssetVPAdapter mAdapter;
    private FragmentManager fm;
    private String[] mCheckTitle = MyApplication.APP_CONTEXT.getResources().
            getStringArray(R.array.check);
    //默认显示第0个fragment
    private int showPosition = 0;
    public static String orderNo = null;
    public static String location = null;
    private List<Asset> mAssetList = new ArrayList<>();
    //新加，上传
    private Button btn_add_check_asset, btn_upload_uncheck;
    private Check check;
    private TaskSyncModel mTaskSyncModel;
    private Dialog mCustomProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asset_list);
        initDataAndView();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }


    private void initDataAndView() {
        initView();
        initData();
    }


    private void initView() {
        tv_uncheck_order_no = findViewById(R.id.tv_uncheck_order_no);
        tv_uncheck_order_create_date = findViewById(R.id.tv_uncheck_order_create_date);
        tv_uncheck_total = findViewById(R.id.tv_check_total_count);
        spLocation = findViewById(R.id.sp_uncheck_location);
        tl_uncheck_asset_list = findViewById(R.id.tl_uncheck_asset_list);
        vp_uncheck_asset_list = findViewById(R.id.vp_uncheck_asset_list);
        btn_add_check_asset = findViewById(R.id.btn_add_check_asset);
        btn_upload_uncheck = findViewById(R.id.btn_upload_uncheck);
        btn_add_check_asset.setOnClickListener(this);
        btn_upload_uncheck.setOnClickListener(this);
    }

    private void initData() {
        initOrderInfo();
        initViewPagerData();
        mTaskSyncModel = new TaskSyncModel();
        mTaskSyncModel.setListener(this);
    }

    private void initOrderInfo() {
        Intent intent = getIntent();
        if (intent != null) {
            orderNo = intent.getStringExtra(Constants.CHECK_ORDER);
            if (orderNo != null) {
                //根据表单号获得未入库表单
                check = CheckDataUtil.getCheckByOrderNo(orderNo);
                if (check != null) {
                    tv_uncheck_order_no.setText(check.getId_());
                    tv_uncheck_order_create_date.setText(check.getCreateTime());
                    mAssetList = CheckDataUtil.getAllAssetByOrderNo(orderNo);
                    if (mAssetList != null) {
                        int total = mAssetList == null ? 0 : mAssetList.size();
                        tv_uncheck_total.setText(total + "");
                    }
//                    if (check.getStatus() != 4) {
//                        btn_upload_uncheck.setVisibility(View.GONE);
//                    }
                }
            } else {
                ToastUtil.toastShort("没有数据");
            }
        }
        List<Room> roomList = BaseDataUtil.getRoomList();
        ArrayAdapter<Room> roomArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, roomList);
        spLocation.setAdapter(roomArrayAdapter);
        spLocation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Room room = (Room) spLocation.getSelectedItem();
                updateAssetData(room.getName());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void updateAssetData(String name) {
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setType(Constants.FIFTLER_ASSET_DATA);
        String[] dataArr = new String[2];
        dataArr[0] = orderNo;
        dataArr[1] = name;
        messageEvent.setMessage(dataArr);
        EventBus.getDefault().post(messageEvent);
    }

    private void initViewPagerData() {
        mAssetList = CheckDataUtil.getAllAssetByOrderNo(orderNo);
        if (mAssetList != null) {
            int total = mAssetList == null ? 0 : mAssetList.size();
            tv_uncheck_total.setText(total + "");
        }
        fm = getSupportFragmentManager();
        if (orderNo != null) {
            List<Asset> unCheckAssetList = CheckDataUtil.getunCheckAssetByOrderNo(orderNo);
            List<Asset> checkedAssetList = CheckDataUtil.getCheckAssetByOrderNo(orderNo);
            int unCheckSize = unCheckAssetList == null ? 0 : unCheckAssetList.size();
            int checkSize = checkedAssetList == null ? 0 : checkedAssetList.size();
            mCheckTitle = new String[]{"待入库(" + unCheckSize + ")",
                    "已入库(" + checkSize + ")"};
        }
        mAdapter = new UncheckAssetVPAdapter(fm, mCheckTitle);
        vp_uncheck_asset_list.setAdapter(mAdapter);
        tl_uncheck_asset_list.setupWithViewPager(vp_uncheck_asset_list);
        tl_uncheck_asset_list.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                vp_uncheck_asset_list.setCurrentItem(tab.getPosition());
                showPosition = tab.getPosition();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.btn_add_check_asset:
                jumpAddCheckDetailActivity();
                break;
            case R.id.btn_upload_uncheck:
                //上传本单
                uploadCheckOrder();
                break;
            default:
                break;
        }
    }


    private void jumpAddCheckDetailActivity() {
        Intent intent = new Intent(this, AddCheckDetailActivity.class);
        intent.putExtra(Constants.CHECK_IN_DETAIL_NO, orderNo);
        startActivity(intent);
    }

    private void uploadCheckOrder() {
        if (mAssetList == null || mAssetList.size() == 0) {
            ToastUtil.toastShort("空入库单不能上传，请添加资产");
            return;
        }
        boolean isNullRfid = false;
        for (int i = 0; i < mAssetList.size(); i++) {
            if (mAssetList.get(i).getRfidNo() == null || "".equals(mAssetList.get(i).getRfidNo())) {
                isNullRfid = true;
                break;
            }
        }
        if (isNullRfid) {
            ToastUtil.toastShort("表单中还有未绑签的RFID，请绑定后提交");
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("是否上传单中所有数据，上传成功后，本单中所有数据会删除。");
        builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                mCustomProgressDialog = CustomProgressDialog.createLoadingDialog(AssetListActivity.this
                        , getString(R.string.is_upload));
                mCustomProgressDialog.setCancelable(false);
                mCustomProgressDialog.show();
                if (check != null) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            List<Check> checkList = new ArrayList<>();
                            checkList.add(check);
                            try {
                                mTaskSyncModel.uploadCheckList(checkList);
                            } catch (Exception e) {
                                ToastUtil.getToast(AssetListActivity.this, e.getMessage());
                                if (mCustomProgressDialog != null) {
                                    mCustomProgressDialog.cancel();
                                }
                            }
                        }
                    }).start();

                }
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!PrefUtils.getBoolean(PrefUtils.SCREEN_STATE, false, AssetListActivity.this)) {
            //息屏之后，所有的数据都不刷新
            initData();
        }
        PrefUtils.putBoolean(PrefUtils.SCREEN_STATE, false, AssetListActivity.this);

        setSelectPosition(1);
    }

    @Override
    public void onFail(String orderNo, OrderType orderType, Exception e, int sum) {
        if (mCustomProgressDialog != null) {
            mCustomProgressDialog.cancel();
        }
        ToastUtil.toastShort(getString(R.string.fail) + orderType + sum + e.getMessage());
    }

    @Override
    public void onSucces(String orderNo, OrderType orderType, int sum) {
        if (mCustomProgressDialog != null) {
            mCustomProgressDialog.cancel();
        }
        ToastUtil.toastShort(getString(R.string.success));
        //成功后，finish本页面
        finish();
    }

    @Override
    protected void onStop() {
        super.onStop();
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (!pm.isInteractive()) {
            PrefUtils.putBoolean(PrefUtils.SCREEN_STATE, true, this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTaskSyncModel != null) {
            mTaskSyncModel.setListener(null);
            mTaskSyncModel = null;
        }
        if (mCustomProgressDialog != null) {
            mCustomProgressDialog.cancel();
        }
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateData(MessageEvent messageEvent) {
    }

}
